<?php
namespace admin;
use controller;

use model\admin\categoryModel;
use model\admin\goodsModel;

class goods extends controller{


    public function get_list(){


        $list = goodsModel::get_list();

        foreach( $list as &$goods ){

            $goods['image'] = WEB_URL . $goods['image'];

        }
        echo json_encode( $list );


    }

    public function info(){

        $goods_id = $_GET['goods_id'];

        $res = [
            'status'=>0,
        ];

        $info = goodsModel::info( $goods_id );


        if( empty($info ) ){

            $res['status'] = 1;
            $res['description'] = '商品不存在';

        }

        $goods_images = goodsModel::get_goods_images( $goods_id );
        $info['goods_images'] = $goods_images;

        $info['description'] = html_entity_decode( $info['description'], ENT_QUOTES, 'UTF-8');
        $info['category'] = [];
        $categories = goodsModel::get_goods_category( $goods_id );
        if( !empty( $categories ) ){

            $filter = [];
            $category_ids = [];
            foreach( $categories as $cat ){
                $category_ids[] = $cat['category_id'];
            }
            $info['category'] = categoryModel::get_path_list( ['category_ids' => $category_ids] );
        }

        $res['product'] = $info;



        echo json_encode( $res );

    }

    public function edit(){

        $goods_id = $_GET['goods_id'];
        $res = [
            'status'=>0,
        ];

        $goods_images = [];
        if( !empty( $_POST['goods_images'] ) ){
            $goods_images = json_decode( $_POST['goods_images'], true );
        }
        $categories = [];
        if( !empty( $_POST['category'] ) ){
            $categories = $_POST['category'];
        }

        $data = [
            'name'          => $_POST['name'],
            'price'         => $_POST['price'],
            'description'   => strip_tags( htmlentities( $_POST['description'] ,ENT_QUOTES, 'UTF-8' )),
            'goods_images'  => $goods_images,
            'image'         => $_POST['image'],
            'status'        => $_POST['status'],
            'category'      => $categories,
        ];



        $edit = goodsModel::edit( $goods_id, $data );

        $res['edit'] = $edit;
        echo json_encode( $res );

    }

    public function search(){

        $filter = [];
        if( !empty( $_GET['filter']) ) {
            $filter['name'] = $_GET['filter'];
        }

        $list = goodsModel::search( $filter );

        echo json_encode( $list );

    }

}